package com.ruan.controller;

import com.ruan.entity.R;
import com.ruan.entity.User;
import com.ruan.service.UserService;
import com.ruan.service.VerifyCodeService;
import com.ruan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;

/**
 * @ClassName:LoginController
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/9/7 10:38
 **/
@RestController
public class LoginController {

    @Autowired
    private VerifyCodeService verifyCodeService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;

    static final String KEY_PREFIX = "user:code:phone:";

    @PostMapping("/getSmsVerifyCode")
    public R<Void> getSmsVerifyCode(String phoneNumber,String type){
        return verifyCodeService.sendVerifyCode(phoneNumber,type);
    }


    @PostMapping("/register")
    public R<Void> register(@Valid User user, String verifyCode){
        String realCode = (redisCache.getCacheObject(KEY_PREFIX+user.getPhoneNumber())).toString();
        if (realCode == null || "".equals(realCode)){
            return new R<>(100,"手机号错误");
        }
        if(!verifyCode.equalsIgnoreCase(realCode)){
            return new R<>(100,"验证码错误");
        }
        return userService.register(user);
    }

    @PostMapping("/login")
    public R<HashMap<String, String>> login(User user){
        return userService.login(user);
    }

    @PostMapping("/smsLogin")
    public R<HashMap<String,String>> smsLogin(String phoneNumber,String verifyCode){
        String realCode = (redisCache.getCacheObject(KEY_PREFIX+phoneNumber)).toString();
        if (realCode == null || "".equals(realCode)){
            return new R<>(100,"手机号错误");
        }
        if(!verifyCode.equalsIgnoreCase(realCode)){
            return new R<>(100,"验证码错误");
        }
        return userService.smsLogin(phoneNumber);
    }

    @RequestMapping("/logout")
    public R<Void> logout(){
        return userService.logout();
    }

}
